package com.senni.config;

import com.alibaba.fastjson.JSON;
import com.senni.response.ActionResult;
import feign.*;
import feign.codec.Decoder;
import feign.codec.Encoder;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;

public class CommonFeignConfiguration {
    public Decoder decoder(){
        return (Response response, Type type)->{
            Response.Body body = response.body();
            String s = Util.toString(body.asReader(Util.UTF_8));
            ActionResult actionResult = JSON.parseObject(s, type);
            if(actionResult==null||actionResult.getCode()!=200){
                Response build = response.toBuilder().status(500).build();
                return build;
            }
            return actionResult;
        };
    }
    public Encoder encoder(){
        return (data,type,requestTemplate)->{
            String method = requestTemplate.method();
            if(data instanceof Map &&!Request.HttpMethod.POST.name().equals(method)){
                Map data1 = (Map) data;
                for (Object o : data1.keySet()) {
                    requestTemplate.query(o.toString(),data1.get(o).toString());
                }
            }else{
                String jsonString = JSON.toJSONString(data);
                requestTemplate.body(jsonString);
            }
        };
    }
    public RequestInterceptor requestInterceptor(){
        return (RequestTemplate requestTemplate)->{

        };
    }
    public InvocationHandlerFactory invocationHandlerFactory(){
        return (Target target, Map<Method, InvocationHandlerFactory.MethodHandler> methodHandlerMap)->{
            return new FeginInvocationHandler(target,methodHandlerMap);
        };
    }
}

